<template>
    <!-- 查询表单 -->
    <div class="search-form">
        <el-card class="search-card">
            <div class="search-container">
                <div class="search-fields">
                    <div class="field-row">
                        <el-button type="success" class="!ml-0" plain @click="openAddDialog">新增</el-button>
                        <el-input v-model="page.TestSchemeName" placeholder="请输入检测方案名称" class="search-input"
                            clearable />
                        <el-select v-model="page.TestKind" placeholder="请输入检测方案类型" class="search-input" clearable>
                            <el-option label="全检" value="1" />
                            <el-option label="抽检" value="2" />
                        </el-select>
                    </div>
                </div>
                <div class="search-actions">
                    <el-button type="primary" @click="list" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                    <el-button type="info" @click="clearSearch" class="clear-btn">
                        <el-icon>
                            <Close />
                        </el-icon>
                        重置
                    </el-button>
                    <el-button type="warning" @click="toggleFullscreen" class="fullscreen-btn">
                        <el-icon>
                            <FullScreen />
                        </el-icon>
                        全屏
                    </el-button>
                </div>
            </div>
        </el-card>
    </div>
    <!-- 新增检验方案 -->
    <el-dialog v-model="dialogFormVisible" title="新增" width="600" :close-on-click-modal="false">
        <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
            <el-form-item label="名称:" prop="testSchemeName">
                <el-input v-model="form.testSchemeName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="类型:" prop="testKind">
                <el-radio-group v-model="form.testKind" @change="onTypeChange">
                    <el-radio :value="1">全检</el-radio>
                    <el-radio :value="2">抽检</el-radio>
                </el-radio-group>
            </el-form-item>
            <!-- 抽检方式和值 -->
            <template v-if="form.testKind === 2">
                <el-form-item label="抽检方式:" prop="testSchemeWay">
                    <el-radio-group v-model="form.testSchemeWay" @change="onSamplingMethodChange">
                        <el-radio :value="1">百分比</el-radio>
                        <el-radio :value="2">间隔</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="值:">
                    <!-- 百分比 -->
                    <div v-if="form.testSchemeWay == 1" class="value-input-group">
                        <el-input-number v-model="form.testSchemeValue" placeholder="请输入值" style="width: 200px;"
                            :min="0" :max="100" />
                        <span class="unit">%</span>
                    </div>
                    <!-- 间隔 -->
                    <div v-else-if="form.testSchemeWay == 2" class="interval-input-group">
                        <span>每间隔</span>
                        <el-input-number v-model="form.intervalValue" placeholder="间隔值"
                            style="width: 120px; margin: 0 8px;" :class="{ 'error-input': intervalValueError }"
                            :min="1" />
                        <span v-if="intervalValueError" class="error-text">请输入数字</span>
                        <span>抽取</span>
                        <el-input-number v-model="form.extract" placeholder="抽取值"
                            style="width: 120px; margin-left: 8px;" :min="1" />
                    </div>
                </el-form-item>
            </template>
            <el-form-item label="检验项目:" prop="testProjectIds">
                <div class="project-select-container">
                    <div class="selected-projects">
                        <el-tag v-for="project in selectedProjects" :key="project.id" closable
                            @close="removeProject(project)" class="project-tag">
                            {{ project.testProName }}
                        </el-tag>
                    </div>
                    <el-button type="primary" @click="openProjectDialog">选择</el-button>
                </div>
            </el-form-item>
            <el-form-item label="描述:">
                <el-input v-model="form.testSchemeDes" type="textarea" :rows="3" placeholder="请输入描述"
                    resize="vertical" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addScheme">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 检验项目选择弹窗 -->
    <el-dialog v-model="showProjectDialog" title="选择检验项目" width="800" :close-on-click-modal="false"
        :before-close="handleProjectDialogClose">
        <div class="transfer-container">
            <div class="transfer-left">
                <div class="transfer-header">
                    <span>可选项目</span>
                    <span class="item-count">{{ availableProjects.length }}项</span>
                </div>
                <div class="transfer-table">
                    <el-table :data="filteredAvailableProjects" @selection-change="handleLeftSelectionChange"
                        ref="leftTableRef" height="300" :row-key="(row: TestProject) => row.id">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="testProName" label="名称" width="80" />
                        <el-table-column type="success" prop="testTypeName" label="检验类型">
                            <template #default="scope">
                                <el-tag :type="getTagType(scope.row.testTypeName)">{{ scope.row.testTypeName }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="testProWorkType" label="检验方式" />
                    </el-table>
                </div>
            </div>
            <div class="transfer-buttons">
                <el-button type="success" @click="moveToRight" :disabled="leftSelected.length === 0">
                    <el-icon>
                        <ArrowRight />
                    </el-icon>
                </el-button>
                <el-button type="success" @click="moveToLeft" :disabled="rightSelected.length === 0">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </el-button>
            </div>
            <div class="transfer-right">
                <div class="transfer-header">
                    <span>已选项目</span>
                    <span class="item-count">{{ selectedProjects.length }}项</span>
                </div>
                <div class="transfer-table">
                    <el-table :data="filteredSelectedProjects" @selection-change="handleRightSelectionChange"
                        ref="rightTableRef" height="300" :row-key="(row: TestProject) => row.id">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="testProName" label="名称" />
                        <el-table-column prop="testTypeName" label="检验类型">
                            <template #default="scope">
                                <el-tag :type="getTagType(scope.row.testTypeName)">
                                    {{ scope.row.testTypeName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showProjectDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmProjectSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改检验方案 -->
    <el-dialog v-model="dialogUpdateVisible" title="修改检验方案" width="600" :close-on-click-modal="false">
        <el-form :model="updateform" :rules="formRules" ref="updateFormRef" label-width="100px">
            <el-form-item label="名称:" prop="testSchemeName">
                <el-input v-model="updateform.testSchemeName" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item label="类型:" prop="testKind">
                <el-radio-group v-model="updateform.testKind" @change="onUpdateTypeChange">
                    <el-radio :value="1">全检</el-radio>
                    <el-radio :value="2">抽检</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 抽检方式和值 -->
            <template v-if="updateform.testKind === 2">
                <el-form-item label="抽检方式:" prop="testSchemeWay">
                    <el-radio-group v-model="updateform.testSchemeWay" @change="onUpdateSamplingMethodChange">
                        <el-radio :value="1">百分比</el-radio>
                        <el-radio :value="2">间隔</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="值:" prop="testSchemeValue">
                    <!-- 百分比模式 -->
                    <div v-if="updateform.testSchemeWay == 1" class="value-input-group">
                        <el-input-number v-model="updateform.testSchemeValue" placeholder="请输入值" style="width: 200px;"
                            :min="0" :max="100" />
                        <span class="unit">%</span>
                    </div>
                    <!-- 间隔模式 -->
                    <div v-else-if="updateform.testSchemeWay == 2" class="interval-input-group">
                        <span>每间隔</span>
                        <el-input-number v-model="updateform.intervalValue" placeholder="间隔值"
                            style="width: 120px; margin: 0 8px;" :class="{ 'error-input': updateIntervalValueError }"
                            :min="1" />
                        <span v-if="updateIntervalValueError" class="error-text">请输入数字</span>
                        <span>抽取</span>
                        <el-input-number v-model="updateform.extract" placeholder="抽取值"
                            style="width: 120px; margin-left: 8px;" :min="1" />
                    </div>
                </el-form-item>
            </template>
            <el-form-item label="检验项目:" prop="testProjectIds">
                <div class="project-select-container">
                    <div class="selected-projects">
                        <el-tag v-for="project in updateSelectedProjects" :key="project.id" closable
                            @close="removeUpdateProject(project)" class="project-tag">
                            {{ project.testProName }}
                        </el-tag>
                    </div>
                    <el-button type="primary" @click="openUpdateProjectDialog">选择</el-button>
                </div>
            </el-form-item>
            <el-form-item label="描述:">
                <el-input v-model="updateform.testSchemeDes" type="textarea" :rows="3" placeholder="请输入描述"
                    resize="vertical" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogUpdateVisible = false">取消</el-button>
                <el-button type="primary" @click="updateSchemeData">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改时的检验项目选择弹窗 -->
    <el-dialog v-model="showUpdateProjectDialog" title="选择检验项目" width="800" :close-on-click-modal="false"
        :before-close="handleUpdateProjectDialogClose">
        <div class="transfer-container">
            <div class="transfer-left">
                <div class="transfer-header">
                    <span>可选项目</span>
                    <span class="item-count">{{ updateAvailableProjects.length }}项</span>
                </div>
                <div class="transfer-table">
                    <el-table :data="filteredUpdateAvailableProjects"
                        @selection-change="handleUpdateLeftSelectionChange" ref="updateLeftTableRef" height="300"
                        :row-key="(row: TestProject) => row.id">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="testProName" label="名称" />
                        <el-table-column prop="testTypeName" label="检验类型">
                            <template #default="scope">
                                <el-tag :type="getTagType(scope.row.testTypeName)">
                                    {{ scope.row.testTypeName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <div class="transfer-buttons">
                <el-button type="success" @click="moveUpdateToRight" :disabled="updateLeftSelected.length === 0">
                    <el-icon>
                        <ArrowRight />
                    </el-icon>
                </el-button>
                <el-button type="success" @click="moveUpdateToLeft" :disabled="updateRightSelected.length === 0">
                    <el-icon>
                        <ArrowLeft />
                    </el-icon>
                </el-button>
            </div>
            <div class="transfer-right">
                <div class="transfer-header">
                    <span>已选项目</span>
                    <span class="item-count">{{ updateSelectedProjects.length }}项</span>
                </div>
                <div class="transfer-table">
                    <el-table :data="filteredUpdateSelectedProjects"
                        @selection-change="handleUpdateRightSelectionChange" ref="updateRightTableRef" height="300"
                        :row-key="(row: TestProject) => row.id">
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="testProName" label="名称" />
                        <el-table-column prop="testTypeName" label="检验类型">
                            <template #default="scope">
                                <el-tag :type="getTagType(scope.row.testTypeName)">
                                    {{ scope.row.testTypeName }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="showUpdateProjectDialog = false">取消</el-button>
                <el-button type="primary" @click="confirmUpdateProjectSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed type="index" label="序号" width="80" />
        <el-table-column prop="testSchemeName" label="检测方案名称" width="150" />
        <el-table-column prop="testKind" label="检测方案类型" width="120">
            <template #default="scope">
                <el-tag v-if="scope.row.testKind == 1">全检</el-tag>
                <el-tag type="success" v-if="scope.row.testKind == 2">抽检</el-tag>
            </template>
        </el-table-column>
        <el-table-column prop="testSchemeWay" label="方式" width="100">
            <template #default="scope">
                <span v-if="scope.row.testKind == 1"></span>
                <span v-if="scope.row.testKind == 2">
                    <el-tag type="warning" v-if="scope.row.testSchemeWay == 1">百分比</el-tag>
                    <el-tag type="info" v-if="scope.row.testSchemeWay == 2">间隔</el-tag>
                    <span type="warning" v-if="scope.row.testSchemeWay == 0"> </span>
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="testSchemeValue" label="值" width="90">
            <template #default="scope">
                <span v-if="scope.row.testSchemeWay == 1">
                    <span v-if="scope.row.testSchemeValue == 0">全部</span>
                    <span v-if="scope.row.testSchemeValue > 0">{{ scope.row.testSchemeValue }}%</span>
                </span>
                <span v-if="scope.row.testSchemeWay == 2"> {{ scope.row.intervalValue * scope.row.extract * 0.1 }}
                </span>
                <span v-if="scope.row.testSchemeValue == 0"> </span>
            </template>
        </el-table-column>
        <el-table-column prop="testSchemeDes" label="备注" width="180" />
        <el-table-column prop="addProp" label="创建人" width="100" />
        <el-table-column prop="addTime" label="创建时间" width="200">
            <template #default="scope">
                {{ moment(scope.row.addTime).format("YYYY年MM月DD日 hh:mm:ss") }}
            </template>
        </el-table-column>
        <el-table-column prop="updTime" label="修改时间" width="200">
            <template #default="scope">
                <span v-if="scope.row.updTime == null"> </span>
                <span v-if="scope.row.updTime != null">
                    {{ moment(scope.row.updTime).format("YYYY年MM月DD日 hh:mm:ss") }}</span>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
                    删除
                </el-button>
                <el-button link type="primary" size="small" @click="updateScheme(scope.row)">修改</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 自定义分页组件 -->
    <div class="pagination-container">
        <div class="pagination-card">
            <div class="pagination-left">
                <span class="total-text">共{{ page.count }}条数据</span>
            </div>
            <div class="pagination-right">
                <span class="total-count">共{{ page.count }}条</span>
                <el-select v-model="page.Pagesize" @change="list()" class="page-size-select">
                    <el-option label="5条/页" :value="5" />
                    <el-option label="10条/页" :value="10" />
                    <el-option label="15条/页" :value="15" />
                    <el-option label="20条/页" :value="20" />
                </el-select>
                <div class="page-navigation">
                    <el-button :disabled="page.Pageindex <= 1" @click="page.Pageindex = page.Pageindex - 1; list()"
                        class="nav-btn">
                        上一页
                    </el-button>

                    <!-- 显示页码 -->
                    <template v-for="p in displayPages" :key="p">
                        <el-button class="page-btn" :class="{ active: p === page.Pageindex }" @click="goToPage(p)">{{ p
                        }}</el-button>
                    </template>

                    <!-- 省略号 -->
                    <span v-if="totalPages > 3 && page.Pageindex < totalPages - 2" class="ellipsis">...</span>

                    <!-- 最后一页 -->
                    <el-button v-if="totalPages > 3 && page.Pageindex < totalPages - 2" class="page-btn"
                        @click="goToPage(totalPages)">{{ totalPages }}</el-button>

                    <el-button :disabled="page.Pageindex >= totalPages"
                        @click="page.Pageindex = page.Pageindex + 1; list()" class="nav-btn">
                        下一页
                    </el-button>
                </div>
                <div class="page-jumper">
                    <span>前往</span>
                    <el-input v-model="jumpPage" @keyup.enter="jumpToPage" class="jump-input" />
                    <span>页</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import Maxios from '@/Http/MesHelp';
import moment from 'moment';
import { onMounted, ref, computed, nextTick } from 'vue';
import { Search, Close, ArrowLeft, ArrowRight, Refresh, FullScreen } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const dialogFormVisible = ref(false)
const dialogUpdateVisible = ref(false)
const showProjectDialog = ref(false)
const showUpdateProjectDialog = ref(false)
const isFullscreen = ref(false)
const jumpPage = ref(1)
const updateFormRef = ref()
const leftTableRef = ref()
const rightTableRef = ref()
const updateLeftTableRef = ref()
const updateRightTableRef = ref()

// 表单数据
const form = ref({
    testSchemeName: "",
    testKind: 1, // 默认全检
    testSchemeWay: null, // 默认百分比
    testSchemeValue: 0,
    intervalValue: 0,
    extract: 0,
    TestSchemeTypeId: ([] as number[]).toString(),
    testSchemeDes: "",
    addProp: ""
})

// 修改表单数据
const updateform = ref({
    id: 0,
    testSchemeName: "",
    testKind: 0,
    testSchemeWay: 0,
    testSchemeValue: 0,
    intervalValue: 0,
    extract: 0,
    TestSchemeTypeId: ([] as number[]).toString(),
    testSchemeDes: "",
})

// 表单验证规则
const formRules = {
    testSchemeName: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    testKind: [
        { required: true, message: '请选择类型', trigger: 'change' }
    ],
    testSchemeWay: [
        { required: true, message: '请选择抽检方式', trigger: 'change' }
    ],
    TestSchemeTypeId: [
        { required: true, message: '请选择检验项目', trigger: 'change' }
    ]
}

// 检验项目类型定义
interface TestProject {
    id: number
    testProName: string
    testTypeName: string
}

// 检验项目相关数据
const availableProjects = ref<TestProject[]>([])
const selectedProjects = ref<TestProject[]>([])
const leftSelected = ref<TestProject[]>([])
const rightSelected = ref<TestProject[]>([])
const leftSearchText = ref('')
const rightSearchText = ref('')
const intervalValueError = ref(false)

// 修改时的检验项目相关数据
const updateAvailableProjects = ref<TestProject[]>([])
const updateSelectedProjects = ref<TestProject[]>([])
const updateLeftSelected = ref<TestProject[]>([])
const updateRightSelected = ref<TestProject[]>([])
const updateLeftSearchText = ref('')
const updateRightSearchText = ref('')
const updateIntervalValueError = ref(false)

// 过滤后的项目列表
const filteredAvailableProjects = computed(() => {
    if (!leftSearchText.value) return availableProjects.value
    return availableProjects.value.filter(project =>
        project.testProName.includes(leftSearchText.value) ||
        project.testTypeName.includes(leftSearchText.value)
    )
})

const filteredSelectedProjects = computed(() => {
    if (!rightSearchText.value) return selectedProjects.value
    return selectedProjects.value.filter(res =>
        res.testProName.includes(rightSearchText.value) ||
        res.testTypeName.includes(rightSearchText.value)
    )
})

// 修改时的过滤后的项目列表
const filteredUpdateAvailableProjects = computed(() => {
    if (!updateLeftSearchText.value) return updateAvailableProjects.value
    return updateAvailableProjects.value.filter(project =>
        project.testProName.includes(updateLeftSearchText.value) ||
        project.testTypeName.includes(updateLeftSearchText.value)
    )
})

const filteredUpdateSelectedProjects = computed(() => {
    if (!updateRightSearchText.value) return updateSelectedProjects.value
    return updateSelectedProjects.value.filter(project =>
        project.testProName.includes(updateRightSearchText.value) ||
        project.testTypeName.includes(updateRightSearchText.value)
    )
})

// 获取标签类型
const getTagType = (typeName: string) => {
    const typeMap: { [key: string]: string } = {
        '音头检测': 'warning',
    }
    return typeMap[typeName] || 'info'
}

// 类型变化处理
const onTypeChange = (value: number) => {
    if (value == 1) {
        // 全检时清空抽检相关字段
        form.value.testSchemeWay = null
        form.value.testSchemeValue = 0
        form.value.intervalValue = 0
        form.value.extract = 0
    } else if (value == 2) {
        // 抽检时设置默认值
        form.value.testSchemeWay = null
    }
}

// 抽检方式变化处理
const onSamplingMethodChange = (value: number) => {
    if (value == 1) {
        form.value.intervalValue = 0
        form.value.extract = 0
        intervalValueError.value = false
    }
}

const pageProps = ref({
    Pageindex: 1,
    Pagesize: 100,
    TestProName: ""
})

// 加载检验项目数据
const loadProjects = () => {
    Maxios.get("/api/TestProject/ListProject", { params: pageProps.value }).then(res => {
        availableProjects.value = res.data.data.list
        console.log('加载检验项目数据成功:', availableProjects.value)
    })
}

// 左侧选择变化
const handleLeftSelectionChange = (selection: TestProject[]) => {
    leftSelected.value = selection
}

// 右侧选择变化
const handleRightSelectionChange = (selection: TestProject[]) => {
    rightSelected.value = selection
}

// 移动到右侧
const moveToRight = () => {
    leftSelected.value.forEach(project => {
        if (!selectedProjects.value.find(p => p.id === project.id)) {
            selectedProjects.value.push(project)
        }
    })
    // 从可用列表中移除
    availableProjects.value = availableProjects.value.filter(project =>
        !leftSelected.value.find(p => p.id === project.id)
    )
    leftSelected.value = []
    nextTick(() => {
        leftTableRef.value?.clearSelection()
    })
}

// 移动到左侧
const moveToLeft = () => {
    rightSelected.value.forEach(project => {
        if (!availableProjects.value.find(p => p.id === project.id)) {
            availableProjects.value.push(project)
        }
    })
    // 从已选列表中移除
    selectedProjects.value = selectedProjects.value.filter(project =>
        !rightSelected.value.find(p => p.id === project.id)
    )
    rightSelected.value = []
    nextTick(() => {
        rightTableRef.value?.clearSelection()
    })
}

// 移除项目
const removeProject = (project: TestProject) => {
    selectedProjects.value = selectedProjects.value.filter(p => p.id !== project.id)
    if (!availableProjects.value.find(p => p.id === project.id)) {
        availableProjects.value.push(project)
    }
}

// 确认项目选择
const confirmProjectSelection = () => {
    form.value.TestSchemeTypeId = (selectedProjects.value.map(p => p.id)).toString()
    showProjectDialog.value = false
}

// 处理项目选择弹窗关闭
const handleProjectDialogClose = (done: () => void) => {
    // 清空选择状态
    leftSelected.value = []
    rightSelected.value = []
    leftSearchText.value = ''
    rightSearchText.value = ''
    done()
}

// 验证间隔值
const validateIntervalValue = () => {
    if (form.value.testSchemeWay == 2) {
        const intervalValue = form.value.intervalValue
        if (intervalValue && !/^\d+$/.test((intervalValue).toString())) {
            intervalValueError.value = true
            return false
        } else {
            intervalValueError.value = false
            return true
        }
    }
    return true
}

// 重置表单
const resetForm = () => {
    form.value = {
        testSchemeName: "",
        testKind: 1,
        testSchemeWay: null,
        testSchemeValue: 0,
        intervalValue: 0,
        extract: 0,
        TestSchemeTypeId: ([] as number[]).toString(),
        testSchemeDes: "",
        addProp: ""
    }
    selectedProjects.value = []
    intervalValueError.value = false
}

// 打开检验项目选择弹窗
const openProjectDialog = async () => {
    console.log('打开检验项目选择弹窗')
    // 如果数据为空，先加载数据
    if (availableProjects.value.length === 0) {
        console.log('检验项目数据为空，重新加载...')
        await loadProjects()
    }
    // 确保数据加载完成后再显示弹窗
    showProjectDialog.value = true
}

// 打开新增弹窗
const openAddDialog = async () => {
    resetForm()
    await loadProjects()
    dialogFormVisible.value = true
}

//添加
const addScheme = () => {
    if (!validateIntervalValue()) {
        ElMessage.error('请输入正确的间隔值')
        return
    }
    // 将响应式对象转换为普通对象，避免循环引用
    if (form.value.testKind == 1) {
        form.value.testSchemeWay = null
        form.value.testSchemeValue = 0
        form.value.intervalValue = 0
        form.value.extract = 0
    }
    const formData = {
        testSchemeName: form.value.testSchemeName,
        testKind: form.value.testKind,
        testSchemeWay: form.value.testSchemeWay,
        testSchemeValue: form.value.testSchemeValue,
        intervalValue: form.value.intervalValue,
        extract: form.value.extract,
        TestSchemeTypeId: form.value.TestSchemeTypeId,
        testSchemeDes: form.value.testSchemeDes,
        addProp: form.value.addProp
    }
    console.log(formData)
    Maxios.post("/api/TestScheme/AddScheme", formData).then(res => {
        if (res.data.code == 200) {
            ElMessage.success(res.data.message)
            dialogFormVisible.value = false
            //重置
            form.value.testSchemeName = ''
            form.value.testKind = 1
            form.value.testSchemeWay = null
            form.value.testSchemeValue = 0
            form.value.intervalValue = 0
            form.value.extract = 0
            form.value.TestSchemeTypeId = ''
            form.value.testSchemeDes = ''
            form.value.addProp = ''
            list()
        } else {
            ElMessage.error(res.data.message)
        }
    })
}

//删除
const handleClick = (id: any) => {
    ElMessageBox.confirm(
        '确定要逻辑删除本条数据吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        Maxios.post("/api/TestScheme/DeleteScheme", { id: id }).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                list()
            }
            else {
                ElMessage.error(res.data.message)
            }
        })
    })


}

const tableData = ref([])

const page = ref({
    Pageindex: 1,
    Pagesize: 10,
    TestSchemeName: "",
    TestKind: null,
    count: 0,
    page: 0
})

//显示
const list = () => {
    Maxios.get("/api/TestScheme/ListScheme", { params: page.value }).then(res => {
        // 确保数据是数组，防止 reduce 错误
        tableData.value = res.data.data?.list || []
        page.value.count = res.data.data?.count || 0
        page.value.page = res.data.data?.page || 0
    })
}

// 清空搜索条件
const clearSearch = () => {
    page.value.TestSchemeName = ''
    page.value.TestKind = null
    page.value.Pageindex = 1
    list()
}

// 全屏切换
const toggleFullscreen = () => {
    isFullscreen.value = !isFullscreen.value
    if (isFullscreen.value) {
        // 进入全屏
        const element = document.documentElement
        if (element.requestFullscreen) {
            element.requestFullscreen()
        } else if ((element as any).webkitRequestFullscreen) {
            (element as any).webkitRequestFullscreen()
        } else if ((element as any).msRequestFullscreen) {
            (element as any).msRequestFullscreen()
        }
    } else {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen()
        } else if ((document as any).webkitExitFullscreen) {
            (document as any).webkitExitFullscreen()
        } else if ((document as any).msExitFullscreen) {
            (document as any).msExitFullscreen()
        }
    }
}

// 跳转到指定页面
const jumpToPage = () => {
    const totalPagesLocal = Math.ceil(page.value.count / page.value.Pagesize)
    if (jumpPage.value >= 1 && jumpPage.value <= totalPagesLocal) {
        page.value.Pageindex = jumpPage.value
        list()
    } else {
        ElMessage.warning(`请输入1到${totalPagesLocal}之间的页码`)
    }
}

// 计算总页数与展示页码
const totalPages = computed(() => Math.max(1, Math.ceil(page.value.count / page.value.Pagesize)))

const displayPages = computed(() => {
    const total = totalPages.value
    const current = page.value.Pageindex

    if (total <= 3) {
        // 总页数小于等于3，显示所有页
        return Array.from({ length: total }, (_, i) => i + 1)
    }

    if (current <= 3) {
        // 当前页在前3页，显示前3页
        return [1, 2, 3]
    }

    if (current >= total - 2) {
        // 当前页在后3页，显示后3页
        return [total - 2, total - 1, total]
    }

    // 当前页在中间，显示当前页前后各1页
    return [current - 1, current, current + 1]
})

const goToPage = (p: number) => {
    if (p < 1 || p > totalPages.value) return
    page.value.Pageindex = p
    list()
}


const updateScheme = async (row: any) => {
    console.log('修改数据:', row)
    // 反填基本信息
    updateform.value.id = row.id
    updateform.value.testSchemeName = row.testSchemeName
    updateform.value.testKind = row.testKind
    updateform.value.testSchemeDes = row.testSchemeDes

    // 处理抽检相关数据
    if (row.testKind === 2) {
        updateform.value.testSchemeWay = row.testSchemeWay
        updateform.value.testSchemeValue = row.testSchemeValue


        if (row.testSchemeWay === 1) {
            // 百分比模式
            updateform.value.testSchemeValue = Number(row.testSchemeValue) || 0
            console.log('百分比值:', updateform.value.testSchemeValue)
        } else if (row.testSchemeWay === 2) {
            // 间隔模式
            const testSchemeValue = row.testSchemeValue

            if (testSchemeValue == 1) {
                updateform.value.intervalValue = Number(row.intervalValue) || 0
                updateform.value.extract = Number(row.extract) || 0
                console.log('解析后的间隔值:', {
                    intervalValue: updateform.value.intervalValue,
                    extract: updateform.value.extract
                })
            } else {
                // 如果不是逗号分隔的字符串，清空字段
                updateform.value.intervalValue = 0
                updateform.value.extract = 0
                console.log('清空间隔值字段')
            }
        }
    }

    // 加载检验项目数据
    await loadUpdateProjects()
    // 如果有检验项目ID，需要加载对应的项目信息
    if (row.testProjectIds || row.testSchemeTypeId) {
        // 优先使用 testSchemeTypeId，如果没有则使用 testProjectIds
        const projectIdsString = row.testSchemeTypeId || row.testProjectIds || ""

        let projectIds: number[] = []
        if (typeof projectIdsString === 'string' && projectIdsString.trim()) {
            projectIds = projectIdsString.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        } else if (Array.isArray(projectIdsString)) {
            projectIds = projectIdsString.map(id => parseInt(id)).filter(id => !isNaN(id))
        }

        console.log('解析的项目ID:', projectIds)

        // 从可用项目中找到对应的项目
        const selectedProjects = updateAvailableProjects.value.filter(project =>
            projectIds.includes(project.id)
        )

        updateSelectedProjects.value = selectedProjects

        // 从可用项目中移除已选择的项目
        updateAvailableProjects.value = updateAvailableProjects.value.filter(project =>
            !projectIds.includes(project.id)
        )
    }
    // 清空搜索文本
    updateLeftSearchText.value = ''
    updateRightSearchText.value = ''
    // 显示修改弹窗
    dialogUpdateVisible.value = true
}

// 修改时的类型变化处理
const onUpdateTypeChange = (value: number) => {
    if (value === 1) {
        // 全检时清空抽检相关字段
        updateform.value.testSchemeWay = 1
        updateform.value.testSchemeValue = 0
        updateform.value.intervalValue = 0
        updateform.value.extract = 0
    } else if (value === 2) {
        // 抽检时设置默认值
        updateform.value.testSchemeWay = 1
    }
}

// 修改时的抽检方式变化处理
const onUpdateSamplingMethodChange = (value: number) => {
    if (value === 1) {
        updateform.value.intervalValue = 0
        updateform.value.extract = 0
        updateIntervalValueError.value = false
    } else if (value === 2) {
        updateform.value.testSchemeValue = 0
    }
}

// 加载修改时的检验项目数据
const loadUpdateProjects = async () => {
    // 添加一些测试数据以防接口有问题
    const testData = [
        { id: 1, testProName: '测试de数据1', testTypeName: '音头检测' },
        { id: 2, testProName: '测试de数据2', testTypeName: '音头检测' },
    ]

    Maxios.get("/api/TestProject/ListProject", { params: pageProps.value }).then(res => {
        console.log('修改时检验项目接口响应:', res.data.data.list)
        // 确保返回的数据是数组
        const data = res.data.data.list
        updateAvailableProjects.value = Array.isArray(data) ? data : testData
        console.log('修改时检验项目数据加载成功:', updateAvailableProjects.value)
    })


}

// 修改时的选择变化处理
const handleUpdateLeftSelectionChange = (selection: TestProject[]) => {
    updateLeftSelected.value = selection
}

const handleUpdateRightSelectionChange = (selection: TestProject[]) => {
    updateRightSelected.value = selection
}

// 修改时的移动函数
const moveUpdateToRight = () => {
    updateLeftSelected.value.forEach(project => {
        if (!updateSelectedProjects.value.find(p => p.id === project.id)) {
            updateSelectedProjects.value.push(project)
        }
    })
    // 从可用列表中移除
    updateAvailableProjects.value = updateAvailableProjects.value.filter(project =>
        !updateLeftSelected.value.find(p => p.id === project.id)
    )
    updateLeftSelected.value = []
    nextTick(() => {
        updateLeftTableRef.value?.clearSelection()
    })
}

const moveUpdateToLeft = () => {
    updateRightSelected.value.forEach(project => {
        if (!updateAvailableProjects.value.find(p => p.id === project.id)) {
            updateAvailableProjects.value.push(project)
        }
    })
    // 从已选列表中移除
    updateSelectedProjects.value = updateSelectedProjects.value.filter(project =>
        !updateRightSelected.value.find(p => p.id === project.id)
    )
    updateRightSelected.value = []
    nextTick(() => {
        updateRightTableRef.value?.clearSelection()
    })
}

// 修改时移除项目
const removeUpdateProject = (project: TestProject) => {
    updateSelectedProjects.value = updateSelectedProjects.value.filter(p => p.id !== project.id)
    if (!updateAvailableProjects.value.find(p => p.id === project.id)) {
        updateAvailableProjects.value.push(project)
    }
}

// 打开修改时的项目选择弹窗
const openUpdateProjectDialog = async () => {
    console.log('打开修改时的检验项目选择弹窗')
    console.log('当前updateAvailableProjects:', updateAvailableProjects.value)

    // 如果数据为空，先加载数据
    if (updateAvailableProjects.value.length === 0) {
        console.log('修改时检验项目数据为空，重新加载...')
        await loadUpdateProjects()
    }

    // 确保数据加载完成后再显示弹窗
    showUpdateProjectDialog.value = true
    console.log('设置showUpdateProjectDialog为true后:', showUpdateProjectDialog.value)
}

// 确认修改时的项目选择
const confirmUpdateProjectSelection = () => {
    updateform.value.TestSchemeTypeId = updateSelectedProjects.value.map(p => p.id).toString()
    showUpdateProjectDialog.value = false
}

// 处理修改时的项目选择弹窗关闭
const handleUpdateProjectDialogClose = (done: () => void) => {
    // 清空选择状态
    updateLeftSelected.value = []
    updateRightSelected.value = []
    updateLeftSearchText.value = ''
    updateRightSearchText.value = ''
    done()
}

// 修改提交
const updateSchemeData = () => {
    // 验证表单
    if (!updateFormRef.value) return
    updateFormRef.value.validate((valid: boolean) => {
        if (!valid) return
        // 将响应式对象转换为普通对象，避免循环引用
        if (form.value.testKind == 1) {
            form.value.testSchemeWay = null
            form.value.testSchemeValue = 0
            form.value.intervalValue = 0
            form.value.extract = 0
        }
        const formData = {
            id: updateform.value.id,
            testSchemeName: updateform.value.testSchemeName,
            testKind: updateform.value.testKind,
            testSchemeWay: updateform.value.testSchemeWay,
            testSchemeValue: updateform.value.testSchemeValue,
            intervalValue: updateform.value.intervalValue,
            extract: updateform.value.extract,
            TestSchemeTypeId: updateform.value.TestSchemeTypeId,
            testSchemeDes: updateform.value.testSchemeDes
        }
        console.log(formData);
        Maxios.post("/api/TestScheme/UpdateScheme", formData).then(res => {
            if (res.data.code == 200) {
                ElMessage.success(res.data.message)
                dialogUpdateVisible.value = false
                list()
            } else {
                ElMessage.error(res.data.message)
            }
        })
    })
}

onMounted(() => {
    list()
})
</script>

<style scoped>
.search-form {
    margin-bottom: 20px;
}

.search-card {
    background: #f5f5f5;
    border-radius: 4px;
}

.search-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
}

.search-fields {
    flex: 1;
}

.field-row {
    display: flex;
    gap: 16px;
    align-items: center;
}

.search-input {
    width: 200px;
}

.search-input :deep(.el-input__wrapper) {
    border-radius: 6px;
    background: white;
}

.search-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.clear-btn {
    background: #f0f0f0;
    border: 1px solid #d9d9d9;
    color: #666;
    border-radius: 6px;
}

.clear-btn:hover {
    background: #e6e6e6;
    border-color: #bfbfbf;
}

.fullscreen-btn {
    background: #fdf6ec;
    border: 1px solid #f5dab1;
    color: #e6a23c;
    border-radius: 6px;
}

.fullscreen-btn:hover {
    background: #faecd8;
    border-color: #eebe77;
    color: #d48806;
}

.search-btn {
    border-radius: 6px;
}

.search-btn:hover {
    opacity: 0.8;
}

/* 分页组件样式 */
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
    width: 100%;
    overflow-x: auto;
}

.pagination-card {
    background: white;
    border-radius: 8px;
    padding: 16px 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    max-width: 100%;
    min-width: 600px;
    flex-wrap: wrap;
    gap: 16px;
}

.pagination-left {
    display: flex;
    align-items: center;
    flex-shrink: 0;
}

.total-text {
    font-size: 14px;
    color: #666;
    font-weight: 500;
    white-space: nowrap;
}

.pagination-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    justify-content: flex-end;
}

.total-count {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
}

.page-size-select {
    width: 100px;
    flex-shrink: 0;
}

.page-size-select :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
}

.page-navigation {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}

.nav-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 4px;
    border: none;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.nav-btn:hover:not(:disabled) {
    color: #409eff;
}

.nav-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.current-page {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: #409eff;
    color: white;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;
    flex-shrink: 0;
}

.page-btn {
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 4px;
    border: none;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    font-size: 14px;
    color: #606266;
}

.page-btn:hover {
    color: #409eff;
}

.page-btn.active {
    background: #409eff;
    color: white;
}

.ellipsis {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    color: #c0c4cc;
    font-size: 14px;
    flex-shrink: 0;
}

.page-jumper {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: #666;
    flex-shrink: 0;
}

.jump-input {
    width: 60px;
}

.jump-input :deep(.el-input__wrapper) {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .pagination-card {
        padding: 12px 16px;
        gap: 12px;
    }

    .pagination-right {
        gap: 8px;
    }

    .total-count {
        display: none;
    }
}

@media (max-width: 768px) {
    .pagination-container {
        justify-content: flex-start;
        padding: 0 16px;
    }

    .pagination-card {
        min-width: 100%;
        padding: 12px;
        flex-direction: column;
        align-items: stretch;
        gap: 12px;
    }

    .pagination-left {
        justify-content: center;
    }

    .pagination-right {
        justify-content: center;
        flex-wrap: wrap;
        gap: 8px;
    }

    .page-size-select {
        width: 80px;
    }

    .jump-input {
        width: 50px;
    }
}

@media (max-width: 480px) {
    .pagination-right {
        flex-direction: column;
        align-items: center;
        gap: 8px;
    }

    .page-navigation {
        order: 1;
    }

    .page-size-select {
        order: 2;
    }

    .page-jumper {
        order: 3;
    }
}

/* 新增弹窗样式 */
.value-input-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.unit {
    color: #666;
    font-size: 14px;
}

.interval-input-group {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
}

.error-input {
    border-color: #f56c6c !important;
}

.error-text {
    color: #f56c6c;
    font-size: 12px;
    margin-left: 8px;
}

.project-select-container {
    display: flex;
    align-items: flex-start;
    gap: 12px;
}

.selected-projects {
    flex: 1;
    min-height: 32px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
}

.project-tag {
    margin: 0;
}

/* 穿梭框样式 */
.transfer-container {
    display: flex;
    gap: 16px;
    height: 400px;
}

.transfer-left,
.transfer-right {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
}

.transfer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f5f7fa;
    border-bottom: 1px solid #dcdfe6;
    font-weight: 500;
}

.item-count {
    color: #666;
    font-size: 12px;
}

.search-bar {
    display: flex;
    gap: 8px;
    padding: 12px 16px;
    border-bottom: 1px solid #dcdfe6;
}

.transfer-table {
    flex: 1;
    overflow: hidden;
}

.transfer-buttons {
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 16px;
    padding: 0 8px;
}

.transfer-buttons .el-button {
    width: 40px;
    height: 40px;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 表单样式调整 */
:deep(.el-form-item__label) {
    font-weight: 500;
}

:deep(.el-radio-group) {
    display: flex;
    gap: 16px;
}

:deep(.el-textarea__inner) {
    resize: vertical;
}
</style>
